#!/usr/bin/env python3
# frequency analysis script for overthewire's krypton wargame
# usage: ./freq.py file
import sys

def find_top_5(table):
    leaders = []
    for item, num in table.items():
        leaders.append(num)
        if len(leaders) > 5:
            leaders.sort(reverse=True)
            leaders.pop()
    for i in leaders:
        for key, val in table.items():
            if i == val:
                print(f'{key}: {i}')

        


def count_bigrams(text):
    bigrams = {}
    length = len(text) - 2
    for char in range(0, length):
        if text[char] != ' ':
            if text[char + 1] != ' ':
                bigram = text[char] + text[char + 1]
                if bigrams.get(bigram) is None:
                    bigrams[bigram] = 1
                else:
                    bigrams[bigram] += 1

    return bigrams

def count_trigrams(text):
    trigrams = {}
    length = len(text) - 3
    for char in range(0, length):
        if text[char] != ' ':
            if text[char + 1] != ' ':
                if text[char + 2] != ' ':
                    trigram = text[char] + text[char + 1] + text[char + 2]
                    if trigrams.get(trigram) is None:
                        trigrams[trigram] = 1
                    else:
                        trigrams[trigram] += 1
    return trigrams


letters = {
	'A': 0,
	'B': 0,
	'C': 0,
	'D': 0,
	'E': 0,
	'F': 0,
	'G': 0,
	'H': 0,
	'I': 0,
	'J': 0,
	'K': 0,
	'L': 0,
	'M': 0,
	'N': 0,
	'O': 0,
	'P': 0,
	'Q': 0,
	'R': 0,
	'S': 0,
	'T': 0,
	'U': 0,
	'V': 0,
	'W': 0,
	'X': 0,
	'Y': 0,
	'Z': 0,
}

if __name__ == '__main__':
    file = sys.argv[1]
    with open(file, 'r', encoding="utf-8") as f:
        text = f.read()
    for i in text:
        if i.isalpha():
            letters[i] += 1
    print("Letter frequencies-----")
    find_top_5(letters)
#     print(letters)

    print("Bigram frequencies-----")
    find_top_5(count_bigrams(text))
#     count_bigrams(text)

    print("Trigram frequencies-----")
    find_top_5(count_trigrams(text))
#     count_trigrams(text)

